import axios from "axios";

// axios.defaults.baseURL = "/weixin";
const baseURL= '/weixin'


// 微信正确请求
interface wxInfo {
  openid: string;
  nickname: string;
  sex: number;
  language: string;
  city: string;
  province: string;
  country: string;
  headimgurl: string;
  privilege: any[];
}
// 微信错误请求
interface wxErrorInfo {
  errcode: number;
  errmsg: string;
}

// 获取accessToken
const getAccessTokenFn = async (code: string) => {
// console.log(code);
const ACCESS_TOKEN_RES = await axios({
    url: baseURL + "/sns/oauth2/access_token",
    params: {
    code: code,
    appid: "wxb30e6b0efd171f58",
    secret: "0cecc634a8178354cf9afa94656fbee3",
    grant_type: "authorization_code",
    },
});
console.log(ACCESS_TOKEN_RES.data, "ACCESS_TOKEN_RES.data");
const data = ACCESS_TOKEN_RES.data;
// 获取失败
return data
};

  // 获取userInfo
const getUserInfoFn = async (
    access_token: string,
    openid: string
  ): Promise<wxInfo | wxErrorInfo> => {
    // console.log(access_token);
    const USERINFO_RES = await axios({
      url: baseURL + "/sns/userinfo",
      params: {
        access_token,
        openid,
        lang: "zh_CN",
      },
    });
    console.log(USERINFO_RES.data, "USERINFO_RES.data");
    const data = USERINFO_RES.data;
    if(data.errcode){
      localStorage.removeItem("encryptedUserToken");
    }
    return data;
  };

export default { axios, getAccessTokenFn, getUserInfoFn };
// 处理 ACCESS_TOKEN_RES 响应
